#include <stdlib.h>
#include <string.h>
#include "trie.h"

NodoTrie* new_NodoTrie()
{
	NodoTrie* n = (NodoTrie*) malloc(sizeof(NodoTrie));
	int i;	
	for (i = 0; i < TAM; i++)
	{
		n->arr[i].hijo = NULL;
		n->arr[i].def = NO;
	}
	return n;
}

void delete_NodoTrie(NodoTrie* nodo)
{
    int i;
	for (i = 0; i < TAM; i++)
    {
        if (nodo->arr[i].hijo != NULL) delete_NodoTrie(nodo->arr[i].hijo);
    }
    free(nodo);
}

Trie* new_Trie()
{
	Trie* t = (Trie*)malloc(sizeof(Trie));
	t->raiz = NULL;
	return t;
}

void delete_Trie(Trie* trie)
{
	if (trie->raiz != NULL)
		delete_NodoTrie(trie->raiz);
	free(trie);
}

char pos_in_arr(char c)
{
	if (c <= '9')
		return c - '0';
	else
		return c - 'a' + (char)10;
}

void insert_in_Trie(Trie* trie, char* str)
{
    NodoTrie** nod = &trie->raiz;
	int size = strlen(str);
    unsigned int i;
	for (i = 0; i < size; i++)
    {
        if (*nod == NULL)
            *nod = new_NodoTrie();
        char k = pos_in_arr(str[i]);
        if (i < size - 1)
            nod = &(((**nod).arr[k]).hijo);
        else
			(**nod).arr[k].def = YES;
    }
}

int belongs_to_Trie(Trie* trie, char* str)
{
    NodoTrie* nod = trie->raiz;
    int esta = (nod != NULL)? YES:NO;
    unsigned int i = 0;
    int size = strlen(str);
	while (esta && i < size)
    {
        char k = pos_in_arr(str[i]);
        if (i < size - 1)
        {
            nod = ((*nod).arr[k]).hijo;
            esta = (nod != NULL)?YES:NO;
        }
        else
            esta = ((*nod).arr[k]).def;
        i++;
    }
    return esta;
}


